package pipeline;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import com.alibaba.fastjson.JSON;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

public class JsonFilePipeline implements Pipeline{

	private String path;
	
	private String file;
	
	public JsonFilePipeline() {
		super();
	}
	
	public JsonFilePipeline(String path, String file){
		this.path = path;
		new File(path).mkdirs();
		this.file = file;
	}
	
	@Override
	public void process(ResultItems resultItems, Task task) {
		String filePath = this.path + "/" + this.file;
        try {
        	FileWriter fileWriter = new FileWriter(getFile(filePath), true);
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.println(JSON.toJSONString(resultItems.getAll()));
            printWriter.flush();
            fileWriter.close();
            printWriter.close();
        } catch (IOException e) {
            System.out.println("写入json文件异常 "+e);
        }
	}
	
	private File getFile(String fullName) {
        checkAndMakeParentDirecotry(fullName);
        return new File(fullName);
    }
	
	private void checkAndMakeParentDirecotry(String fullName) {
        int index = fullName.lastIndexOf("/");
        if (index > 0) {
            String path = fullName.substring(0, index);
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
    }

}
